package cn.cds.withyou.base.provider;

import android.content.ContentProvider;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.support.annotation.Nullable;

import cn.cds.withyou.base.Application;
import cn.cds.withyou.base.SqliteOpenHelper;
import cn.cds.withyou.lib.Constants;

public abstract class BaseProvider extends ContentProvider {

    private SqliteOpenHelper mDBHelper;

    @Override
    public boolean onCreate() {
        mDBHelper = new SqliteOpenHelper(getContext());
        return true;
    }

    @Nullable
    @Override
    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
        return mDBHelper.getReadableDatabase()
                .query(getTableName(), projection, selection, selectionArgs, null, null, sortOrder);
    }

    @Nullable
    @Override
    public String getType(Uri uri) {
        return uri.toString();
    }

    @Nullable
    @Override
    public Uri insert(Uri uri, ContentValues values) {
        long result = mDBHelper.getWritableDatabase()
                .insert(getTableName(), null, values);
        return Uri.parse(uri.toString() + "/" + result);
    }

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        return mDBHelper.getWritableDatabase()
                .delete(getTableName(), selection, selectionArgs);
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
        return mDBHelper.getWritableDatabase()
                .update(getTableName(), values, selection, selectionArgs);
    }

    protected abstract String getTableName ();
}
